package ru.fivestarter.model.diary;

import java.util.Calendar;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TemporalType;

import ru.fivestarter.entities.diary.GoalMonth;
import ru.fivestarter.entities.diary.GoalWeek;
import ru.fivestarter.entities.diary.GoalYear;
import ru.fivestarter.entities.diary.Goals;
import ru.fivestarter.entities.diary.StructGoals;
import ru.fivestarter.entities.leonardo.UsersLeo;


/**
 * Session Bean implementation class BusinessDiary
 */
@Stateless
@LocalBean
public class BusinessDiary {
	@PersistenceContext
	private EntityManager em;
	private UsersLeo user;
	private List<GoalMonth> gMonth;
	private List<Goals> goals;
	private List<GoalWeek> gWeek;
	private List<GoalYear> gYear;
	private StructGoals structGoalsResult;
    /**
     * Default constructor. 
     */
    public BusinessDiary() {
        // TODO Auto-generated constructor stub
    }
    
    public StructGoals getGoals(String login, Calendar dateOfGoal){//Получение целей конкретного пользователя, в конкретный день. решить одним запросом JPQL - проблемно. будем прорываться используя много малых и соединяя из в результат.
    	try{
    		user=em.createNamedQuery("UsersLeo.findUsersLeoForLogin",UsersLeo.class).setParameter("log", login).getSingleResult();
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	try{
    		gMonth=em.createNamedQuery("GoalMonth.findByYearGoalMonthUser", GoalMonth.class).setParameter("yearD", dateOfGoal.get(Calendar.YEAR)).setParameter("monthD",dateOfGoal.get(Calendar.MONTH)).setParameter("userD", user).getResultList();   
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	if(gMonth.isEmpty()){
    		gMonth.add(new GoalMonth());
    	}
    	try{
    		goals=em.createNamedQuery("Goals.findByDateUser", Goals.class).setParameter("dataD", dateOfGoal,TemporalType.DATE).setParameter("userD", user).getResultList();
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	if(goals.isEmpty()){
    		goals.add(new Goals());
    	}
    	try{
    		gWeek=em.createNamedQuery("GoalWeek.findByYearGoalWeekOfYear", GoalWeek.class).setParameter("yearD", dateOfGoal.get(Calendar.YEAR)).setParameter("weekD", dateOfGoal.get(Calendar.WEEK_OF_YEAR)).setParameter("userD", user).getResultList();
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	if(gWeek.isEmpty()){
    		gWeek.add(new GoalWeek());
    	}
    	try{
    		gYear=em.createNamedQuery("GoalYear.findByYearGoalUser", GoalYear.class).setParameter("yearD", dateOfGoal.get(Calendar.YEAR)).setParameter("userD", user).getResultList();
    	}catch (Exception e) {
			// TODO: handle exception
		}
    	if(gYear.isEmpty()){
    		gYear.add(new GoalYear());
    	}
    	structGoalsResult = new StructGoals();
    	structGoalsResult.setAward(goals.get(0).getAward());
    	structGoalsResult.setBeefsteak(goals.get(0).getBeefsteak());
    	structGoalsResult.setEventDay(goals.get(0).getEventDay());
    	structGoalsResult.setFixTask(goals.get(0).getFixTask());
    	structGoalsResult.setFrog(goals.get(0).getFrog());
    	structGoalsResult.setGoalDay(goals.get(0).getGoalDay());
    	structGoalsResult.setToughTask(goals.get(0).getToughTask());
    	structGoalsResult.setGoalMonth(gMonth.get(0).getGoal());
    	structGoalsResult.setGoalWeek(gWeek.get(0).getGoal());
    	structGoalsResult.setGoalYear(gYear.get(0).getGoal());
    	structGoalsResult.setDataDiary(dateOfGoal);
    	return structGoalsResult;
    	
    }
    public void setGoals(String login, StructGoals myGoal){//Сохранение данных пользователя, с заменой существующих данных.
    	try{
    		user=em.createNamedQuery("UsersLeo.findUsersLeoForLogin",UsersLeo.class).setParameter("log", login).getSingleResult();
    	}catch (Exception e) {
			// TODO: handle exception
    		System.out.println(e.toString());
		}
    	List<Goals> myGoals=null;
    	try{
    		myGoals=em.createNamedQuery("Goals.findByDateUser",Goals.class).setParameter("dataD",myGoal.getDataDiary(),TemporalType.DATE).setParameter("userD", user).getResultList();
    	}
    	catch (Exception e) {
			// TODO: handle exception
    		System.out.println(e.toString());
		}
    	if(myGoals.isEmpty()){    	
    		myGoals.add(new Goals());
    	
    	}
    	// в этом блоке обновляется содержимое сущности, а перед этим они изменяются. чет не очень!!! это все благодаря отказу от практики составного ключа
    	myGoals.get(0).setAward(myGoal.getAward());
		myGoals.get(0).setBeefsteak(myGoal.getBeefsteak());
		myGoals.get(0).setEventDay(myGoal.getEventDay());
		myGoals.get(0).setFixTask(myGoal.getFixTask());
		myGoals.get(0).setFrog(myGoal.getFrog());
		myGoals.get(0).setGoalDay(myGoal.getGoalDay());
		myGoals.get(0).setToughTask(myGoal.getToughTask());
		myGoals.get(0).setDataDiary(myGoal.getDataDiary());
		myGoals.get(0).setUser(user);
		em.merge(myGoals.get(0));
    	
    	List<GoalMonth> myGoalMonth = null;
    	try{
    		myGoalMonth= em.createNamedQuery("GoalMonth.findByYearGoalMonthUser",GoalMonth.class).setParameter("yearD", myGoal.getDataDiary().get(Calendar.YEAR)).setParameter("monthD", myGoal.getDataDiary().get(Calendar.MONTH)).setParameter("userD", user).getResultList();
    	}
    	catch (Exception e) {
			// TODO: handle exception
    		System.out.println(e.toString());
		}
    	if(myGoalMonth.isEmpty()){    	
    		myGoalMonth.add(new GoalMonth());
    		
    	}
    	// в этом блоке обновляется содержимое сущности, а перед этим они изменяются. чет не очень!!! это все благодаря отказу от практики составного ключа
		myGoalMonth.get(0).setGoal(myGoal.getGoalMonth());
		myGoalMonth.get(0).setMonth(myGoal.getDataDiary().get(Calendar.MONTH));
		myGoalMonth.get(0).setYear(myGoal.getDataDiary().get(Calendar.YEAR));
		myGoalMonth.get(0).setUser(user);
		em.merge(myGoalMonth.get(0));
    	
    	List<GoalWeek> myGoalWeek = null;
    	try{
    		myGoalWeek=em.createNamedQuery("GoalWeek.findByYearGoalWeekOfYear",GoalWeek.class).setParameter("yearD", myGoal.getDataDiary().get(Calendar.YEAR)).setParameter("weekD", myGoal.getDataDiary().get(Calendar.WEEK_OF_YEAR)).setParameter("userD", user).getResultList();
    	}
    	catch (Exception e) {
			// TODO: handle exception
    		System.out.println(e.toString());
		}
    	if(myGoalWeek.isEmpty()){    	
    		myGoalWeek.add(new GoalWeek());
        	
    	}
		myGoalWeek.get(0).setGoal(myGoal.getGoalWeek());
		myGoalWeek.get(0).setWeek_of_year(myGoal.getDataDiary().get(Calendar.WEEK_OF_YEAR));
		myGoalWeek.get(0).setYear(myGoal.getDataDiary().get(Calendar.YEAR));
		myGoalWeek.get(0).setUser(user);
		em.merge(myGoalWeek.get(0));
    	
    	List<GoalYear> myGoalYear = null;
    	try{
    		myGoalYear=em.createNamedQuery("GoalYear.findByYearGoalUser",GoalYear.class).setParameter("yearD", myGoal.getDataDiary().get(Calendar.YEAR)).setParameter("userD", user).getResultList();
    	}
    	catch (Exception e) {
			// TODO: handle exception
    		e.toString();
		}
    	if(myGoalYear.isEmpty()){
    		myGoalYear.add(new GoalYear());
    		
    	}
    	myGoalYear.get(0).setGoal(myGoal.getGoalYear());
		myGoalYear.get(0).setYear(myGoal.getDataDiary().get(Calendar.YEAR));
		myGoalYear.get(0).setUser(user);
		em.merge(myGoalYear.get(0));
    	
    }
}
